package top.zhangjianyong.tools.config.filter;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import top.zhangjianyong.tools.user.StockUserChecker;
import top.zhangjianyong.tools.user.SystemUserChecker;
import top.zhangjianyong.tools.user.UserChecker;
import top.zhangjianyong.tools.utils.ApiResponse;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * @author ： zhangjianyong
 * @date ： 2022/4/25 9:55 上午
 */
@SuppressWarnings("rawtypes")
@Slf4j
public class UserFilter implements Filter {

    private final static List<UserChecker> USER_FILTER_HANDLERS = Arrays.asList(new StockUserChecker(), new SystemUserChecker());


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException {
        log.info("用户登陆过滤器。。。");
        try {

            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String uri = request.getRequestURI();
            log.info("uri:{}", uri);
            if (USER_FILTER_HANDLERS.stream().noneMatch(userFilterChecker -> userFilterChecker.doCheck(uri))) {
                printResponse(ApiResponse.fail(999, "未登录"), servletResponse);
                return;
            }

            filterChain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            printResponse(ApiResponse.fail(e.getMessage()), servletResponse);
        }

    }

    public void printResponse(ApiResponse apiResponse, ServletResponse response) throws IOException {
        response.getOutputStream().write(JSONObject.toJSONString(apiResponse).getBytes(StandardCharsets.UTF_8));
    }
}
